# -*- coding: utf_8 -*-

from wxpy import Bot
from wxpy import Tuling
import PIL.Image as Image
import os
import sys
import math
import jieba
import numpy as np
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS
import time
import platform


def draw_heart():
    file_mask = curr_dir+'/heart.png'
    t = np.linspace(0, math.pi, 1000)
    x = np.sin(t)
    y = np.cos(t) + np.power(x, 2.0 / 3)
    plt.figure(figsize=(20, 20))
    plt.plot(x, y, color='red', linewidth=2)
    plt.plot(-x, y, color='red', linewidth=2)
    plt.ylim(-1.5, 2)
    plt.xlim(-1.5, 1.5)
    plt.fill_between(x, y, facecolor='pink')
    plt.fill_between(-x, y, facecolor='pink')
    plt.axis('off')  # 取消显示坐标轴
    plt.savefig(file_mask)
    # plt.show()
    return file_mask


def make_wordcloud(text, file_wordcloud):
    #生成词云准备
    font = set_font()
    file_mask = draw_heart()
    mask = np.array(Image.open(file_mask))
    jieba.del_word('男男女女')
    jieba.del_word('男女')
    jieba.del_word('女女')
    jieba.del_word('男男女')
    jieba.suggest_freq(('男', '女'), True)
    wordlist_after_jieba = jieba.cut(text, cut_all=False)
    wl_space_split = " ".join(wordlist_after_jieba).replace(
        "class", "").replace("span", "").replace("emoji", "")
    stopwords = set(STOPWORDS)
    stopwords.discard("男")
    stopwords.discard("女")
    wc = WordCloud(font_path=font, background_color="white", margin=5, width=1280, height=800,
                   max_words=2000, mask=mask, stopwords=stopwords).generate(wl_space_split)
    wc.to_file(file_wordcloud)
    print("[ * ] 词云图片已经保存为{0}".format(file_wordcloud))
    plt.imshow(wc)
    plt.axis("off")
    # plt.show()
    return file_wordcloud


def get_avatar(all_friends, new_dir):

    #获取好友头像信息并存储在FriendImgs目录中

    print("[ * ] 正在提取{0}个好友的头像......".format(len(all_friends)))
    for n, friend in enumerate(all_friends):
        print(
            "[ * ] 正在提取好友{0}-{1}的头像............\r".format(n, friend.name), end="\r")
        file_avatar = new_dir + str(n) + ".jpg"
        friend.get_avatar(file_avatar)
        if os.path.getsize(file_avatar) == 0:
            friend.get_avatar(file_avatar)
            pass
        if os.path.getsize(file_avatar) == 0:
            print("[ * ] 好友{0}-{1}的头像为空！！！".format(n, friend.name))
            os.remove(file_avatar)

    print("[ * ] 好友的头像已经存储在{0}目录下。".format(new_dir))


def get_signature(all_friends):

    #获取好友签名
    print("[ * ] 正在提取{0}个好友的签名......".format(len(all_friends)))
    info = ""
    for i,friend in enumerate(all_friends):
        signature=friend.signature
        print(
            "[ * ] 正在提取好友{0}-{1}的签名：{2}\r".format(i, friend.name,signature), end="\r")
        info = info+str(signature)
    return info


def get_sex(all_friends):

    #获取好友性别
    print("[ * ] 正在提取{0}个好友的性别......".format(len(all_friends)))
    info = ""
    
    for i,friend in enumerate(all_friends):
        sex=("男性" if friend.sex == 1 else "女性")
        print(
            "[ * ] 正在提取好友{0}-{1}的性别：{2}\r".format(i, friend.name,sex), end="\r")
        info = info+sex
    return info


def make_avatar_wall(count_friend, new_dir):
    # 准备生成微信好友头像墙的尺寸，正方形
    #比如：定义高和宽都是17个头像，每个头像高50，宽50，因此正方形图像大小为17*50=850

    high_width = 17  # 可以自定义修改
    high_width = math.ceil(count_friend**0.5)
    image = Image.new("RGB", (high_width * 50, high_width * 50))

    # 定义初始图片的位置
    x = 0
    y = 0

    # 获取下载的头像文件
    ls = os.listdir(new_dir)

    # 遍历文件夹的图片
    for file_names in ls:
        try:
            # 依次打开图片
            img = Image.open(new_dir + file_names)
        except IOError:
            continue
        else:
            # 重新设置图片的大小
            img = img.resize((50, 50), Image.ANTIALIAS)
            # 将图片粘贴到最终的照片墙上
            image.paste(img, (x * 50, y * 50))
            # 设置每一行排high_width个图像
            x += 1
            if x == high_width:
                x = 0
                y += 1
    # 保存图片为WeChat_Friends.jpg
    file_avatar_wall = curr_dir + "/wxfriendwall.jpg"
    img = image.save(file_avatar_wall)
    print("[ * ] 朋友圈全家福已经保存为{0}".format(file_avatar_wall))
    img = Image.open(file_avatar_wall)
    # img.show()
    return file_avatar_wall


def set_font():
    sysstr = platform.platform()
    if "Windows" in sysstr:
        font = "C:\\Windows\\Fonts\\STFANGSO.ttf"  # 不加这一句显示口字形乱码
    else:
        font = "/usr/share/fonts/msyh.ttf"
    return font


def send_wordcloud(file_wordcloud, notify_text):
    me.send_image(file_wordcloud)
    print("[ * ] 已发送{0}至微信......".format(notify_text))


def start_auto_reply(nickname):
    #  注册获得个人的图灵机器人key 填入
    # 此功能暂时无效
    tuling = Tuling(api_key='5e589b0ccbfd4e5f801b7ae7417d4f48')
    someone = all_friends .search(nickname)
    @bot.register(someone)
    def reply_my_friend(msg):
        print(msg)
        tuling.do_reply(msg)
    bot.join()


tips = """
0x00 程序功能
1.扫二维码即可提取微信好友头像，生成正方形头像墙。墙的大小自动根据好友的数量来设定。
2.提取好友签名，制作词云。
3.提取好友性别，制作词云。
0x01 本程序python3环境运行，需要pip安装以下依赖库：wxpy,pillow,jieba,numpy,matplotlib,wordcloud
"""

print(tips)
time.sleep(3)

# 获取当前路径信息
curr_dir = sys.path[0]
# 如果FriendImgs目录不存在就创建一个，用来存储好友头像
new_dir = curr_dir + "/../FriendImgs/"
if not os.path.exists(new_dir):
    os.mkdir(new_dir)
# 初始化机器人，扫码登陆微信，适用于Windows系统
#bot = Bot()
# Linux系统，执行登陆请调用下面的这句
bot = Bot(qr_path="qr.png",cache_path="../wx.cd")
me = bot.self
all_friends = bot.friends(update=True)
# 取得微信好友头像
get_avatar(all_friends, new_dir)

# 生成微信好友头像墙并发送给自己
file_avatar_wall = make_avatar_wall(len(all_friends), new_dir)
send_wordcloud(file_avatar_wall, "微信好友全家福")

#生成微信好友签名词云并发给自己
file_wordcloud = curr_dir + "/signature_wordcloud.png"
file_wordcloud = make_wordcloud(get_signature(all_friends), file_wordcloud)
send_wordcloud(file_wordcloud, "微信好友签名词云图")

#生成微信好友性别词云并发给自己
file_wordcloud = curr_dir + "/sex_wordcloud.png"
file_wordcloud = make_wordcloud(get_sex(all_friends), file_wordcloud)
send_wordcloud(file_wordcloud, "微信好友性别词云图")

# 使用图灵机器人自动与指定好友聊天
# start_auto_reply("秋水伊人")
print("退出微信......", end="")
bot.logout()
